<template>
  <div class="booking-ticket">
    <!-- 滚动通知 -->
    <div class="notice-banner">
      <button class="back-button" @click="goBack">
        <span class="back-icon">‹</span>
      </button>
      <div class="notice-icon">📢</div>
      <div class="notice-content">
        <div class="scrolling-text">
          每个时段仅限6人体验 | 可预约多场 | 建议提前15分钟到场 | 免费预约，先到先得
        </div>
      </div>
    </div>

    <!-- 订单填写区域 -->
    <div class="booking-main">
      
      <!-- 参观日期选择组件 -->
      <DateSelector 
        :selectedDate="selectedDate"
        @update:selectedDate="selectedDate = $event"
        @dateChanged="onDateChanged"
      />

      <!-- 门票信息组件 -->
      <TicketInfo />

      <!-- 时间段选择组件 -->
      <TimeSlotSelector 
        :selectedTimeSlot="selectedTimeSlot"
        @update:selectedTimeSlot="selectedTimeSlot = $event"
        :timeSlots="allTimeSlots"
        @timeSlotChanged="onTimeSlotChanged"
      />

      <!-- 个人信息选择组件 -->
      <PersonalInfoSelector 
        :selectedPersonalInfo="selectedPersonalInfo"
        @update:selectedPersonalInfo="selectedPersonalInfo = $event"
        :personalInfoList="personalInfoList"
        :personalInfoLoading="personalInfoLoading"
        @refreshPersonalInfo="loadUserPersonalInfo"
        @showPersonalInfoForm="showPersonalInfoForm = true"
        @editPersonalInfo="editPersonalInfo"
      />

      <!-- 购买须知 -->
      <div class="purchase-notice">
        <div class="notice-link" @click="noticeVisible = true">
          预定须知 >
        </div>
      </div>

      <!-- 预约按钮 -->
      <div class="payment-section">
        <el-button 
          type="primary" 
          size="large" 
          @click="confirmBooking"
          class="payment-button"
          :disabled="!canSubmit"
        >
          确认预约
        </el-button>
      </div>
    </div>

    <!-- 个人信息填写页面组件 -->
    <PersonalInfoForm 
      v-if="showPersonalInfoForm"
      @save="handlePersonalInfoSave"
      @cancel="handlePersonalInfoCancel"
    />

    <!-- 个人信息编辑页面组件 -->
    <EditPersonalInfoForm 
      v-if="showEditPersonalInfoForm"
      :personalInfo="editingPersonalInfo"
      @save="handleEditPersonalInfoSave"
      @cancel="handleEditPersonalInfoCancel"
    />

    <!-- 购买须知弹窗组件 -->
    <NoticeDialog 
      :visible="noticeVisible"
      @update:visible="noticeVisible = $event"
    />

    <!-- 确认预约弹窗组件 -->
    <BookingConfirmDialog 
      :visible="confirmBookingVisible"
      @update:visible="confirmBookingVisible = $event"
      :bookingSummary="bookingSummary"
      @confirm="submitBooking"
      @cancel="confirmBookingVisible = false"
    />

    <!-- 加载组件 -->
    <LoadingSpinner 
      :visible="isLoading" 
      :title="loadingTitle" 
      :message="loadingMessage" 
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 导入子组件
import DateSelector from './ticket/DateSelector.vue'
import TimeSlotSelector from './ticket/TimeSlotSelector.vue'
import PersonalInfoSelector from './ticket/PersonalInfoSelector.vue'
import BookingConfirmDialog from './ticket/BookingConfirmDialog.vue'
import NoticeDialog from './ticket/NoticeDialog.vue'
import TicketInfo from './ticket/TicketInfo.vue'

// 导入原有组件
import PersonalInfoForm from './PersonalInfoForm.vue'
import EditPersonalInfoForm from './EditPersonalInfoForm.vue'
import LoadingSpinner from './LoadingSpinner.vue'

// 导入API
import { getTimeSlotsByDate, bookTimeSlot, checkUserBooking } from '@/api/booking.js'
import { getPersonalInfoByToken } from '@/api/personalInfo.js'
import { getUserStore } from '@/stores/user.js'

// 接收props
const props = defineProps({
  selectedTimeSlot: {
    type: Object,
    default: null
  }
})

// 定义emit事件
const emit = defineEmits(['showBookingDetails', 'switchTab'])

// 获取用户store
const userStore = getUserStore()

// 响应式数据
const selectedDate = ref('')
const selectedTimeSlot = ref('')
const selectedPersonalInfo = ref(null)
const noticeVisible = ref(false)
const confirmBookingVisible = ref(false)
const showPersonalInfoForm = ref(false)
const showEditPersonalInfoForm = ref(false)
const editingPersonalInfo = ref(null)

// 加载状态
const isLoading = ref(false)
const loadingTitle = ref('加载中')
const loadingMessage = ref('请稍候，正在为您准备精彩内容...')

// 个人信息相关
const personalInfoList = ref([])
const personalInfoLoading = ref(false)

// 用户设备标识
const userToken = ref('')

// 时间段数据
const allTimeSlots = ref([])

// 显示加载
const showLoading = (title = '加载中', message = '请稍候，正在为您准备精彩内容...') => {
  loadingTitle.value = title
  loadingMessage.value = message
  isLoading.value = true
}

// 隐藏加载
const hideLoading = () => {
  isLoading.value = false
}

// 生成设备指纹
const generateDeviceFingerprint = () => {
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  ctx.textBaseline = 'top'
  ctx.font = '14px Arial'
  ctx.fillText('设备指纹', 2, 2)
  
  const fingerprint = [
    navigator.userAgent,
    navigator.language,
    screen.width + 'x' + screen.height,
    new Date().getTimezoneOffset(),
    canvas.toDataURL()
  ].join('|')
  
  // 生成简化的哈希
  let hash = 0
  for (let i = 0; i < fingerprint.length; i++) {
    const char = fingerprint.charCodeAt(i)
    hash = ((hash << 5) - hash) + char
    hash = hash & hash
  }
  
  return 'device_' + Math.abs(hash).toString(36) + '_' + Date.now().toString(36)
}

// 获取或生成用户标识
const getUserToken = () => {
  let token = localStorage.getItem('userToken')
  if (!token) {
    token = generateDeviceFingerprint()
    localStorage.setItem('userToken', token)
  }
  return token
}

// 获取当前日期
const getCurrentDate = () => {
  return new Date()
}

// 获取格式化日期字符串
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 检查日期是否在可预约范围内
const isDateBookable = (date) => {
  const targetDate = new Date(date)
  const startDate = new Date(2025, 5, 25) // 2025年6月25日
  const endDate = new Date(2025, 6, 23) // 2025年7月22日
  const currentDate = getCurrentDate()
  
  return targetDate >= startDate && 
         targetDate < endDate && 
         targetDate >= new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate())
}

// 加载时间段数据
const loadTimeSlots = async (date) => {
  if (!date) return
  
  try {
    showLoading('加载中', '正在获取可用时间段...')
    
    const response = await getTimeSlotsByDate(date)
    
    if (response.code !== 200) {
      ElMessage.error(response.message || '获取时间段失败')
      return
    }
    
    const timeSlots = response.data || []
    
    // 处理时间段数据
    allTimeSlots.value = timeSlots.map(slot => {
      const formatTime = (timeStr) => {
        if (typeof timeStr === 'string') {
          return timeStr.slice(0, 5)
        }
        return timeStr
      }
      
      return {
        id: slot.id,
        time: `${formatTime(slot.startTime)}-${formatTime(slot.endTime)}`,
        remaining: slot.maxCapacity - slot.bookedCount,
        period: slot.periodName,
        periodName: slot.periodName,
        maxCapacity: slot.maxCapacity,
        bookedCount: slot.bookedCount,
        isAvailable: slot.isAvailable && !slot.isLocked,
        isLocked: slot.isLocked,
        slotDate: slot.slotDate
      }
    })
    
    console.log('时间段加载成功:', allTimeSlots.value.length)
    
  } catch (error) {
    console.error('加载时间段数据失败:', error)
    ElMessage.error('加载时间段数据失败，请重试')
  } finally {
    hideLoading()
  }
}

// 获取当前用户的个人信息
const loadUserPersonalInfo = async () => {
  const token = userStore.userToken.value
  if (!token || typeof token !== 'string') {
    console.log('ℹ️ userToken无效，无法获取个人信息:', token)
    return
  }

  personalInfoLoading.value = true
  try {
    console.log('🔍 正在获取用户个人信息, userToken:', token)
    const response = await getPersonalInfoByToken(token)
    
    if (response.code === 200 && response.data) {
      const personalInfo = response.data
      const existingInfo = personalInfoList.value.find(info => info.id === personalInfo.id)
      
      if (!existingInfo) {
        // 处理languages字段
        if (personalInfo.languages) {
          try {
            personalInfo.languagesArray = JSON.parse(personalInfo.languages)
          } catch (e) {
            personalInfo.languagesArray = []
          }
        } else {
          personalInfo.languagesArray = []
        }
        
        personalInfoList.value.push(personalInfo)
        console.log('✅ 已加载用户个人信息:', personalInfo)
      }
      
      // 自动选择默认个人信息
      if (personalInfo.isDefault) {
        selectedPersonalInfo.value = personalInfo
        console.log('✅ 已自动选择默认个人信息')
      }
    } else {
      console.log('ℹ️ 用户暂无个人信息记录')
    }
  } catch (error) {
    console.error('❌ 获取用户个人信息失败:', error)
  } finally {
    personalInfoLoading.value = false
  }
}

// 是否可以提交
const canSubmit = computed(() => {
  return selectedDate.value && selectedTimeSlot.value && selectedPersonalInfo.value
})

// 日期变化事件
const onDateChanged = (date) => {
  selectedTimeSlot.value = '' // 重置时间段选择
  loadTimeSlots(date)
}

// 时间段变化事件
const onTimeSlotChanged = (slot) => {
  console.log('选择的时间段:', slot)
}

// 处理个人信息保存
const handlePersonalInfoSave = (newPersonalInfo) => {
  personalInfoList.value.push(newPersonalInfo)
  selectedPersonalInfo.value = newPersonalInfo
  showPersonalInfoForm.value = false
  ElMessage.success('个人信息已保存并自动选中')
  
  setTimeout(() => {
    loadUserPersonalInfo()
  }, 500)
}

// 处理个人信息表单取消
const handlePersonalInfoCancel = () => {
  showPersonalInfoForm.value = false
}

// 编辑个人信息
const editPersonalInfo = (info) => {
  editingPersonalInfo.value = info
  showEditPersonalInfoForm.value = true
}

// 处理个人信息编辑保存
const handleEditPersonalInfoSave = (updatedPersonalInfo) => {
  const index = personalInfoList.value.findIndex(info => info.id === updatedPersonalInfo.id)
  if (index !== -1) {
    personalInfoList.value[index] = updatedPersonalInfo
  }
  
  if (selectedPersonalInfo.value && selectedPersonalInfo.value.id === updatedPersonalInfo.id) {
    selectedPersonalInfo.value = updatedPersonalInfo
  }
  
  showEditPersonalInfoForm.value = false
  editingPersonalInfo.value = null
  ElMessage.success('个人信息更新成功')
}

// 处理个人信息编辑取消
const handleEditPersonalInfoCancel = () => {
  showEditPersonalInfoForm.value = false
  editingPersonalInfo.value = null
}

// 预约摘要
const bookingSummary = computed(() => {
  if (!selectedDate.value || !selectedTimeSlot.value || !selectedPersonalInfo.value) {
    return {
      date: '',
      timeSlot: '',
      visitorInfo: '',
      phone: ''
    }
  }
  
  const formatBookingDate = (dateString) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const weekDay = getWeekDay(dateString)
    return `${year}年${month}月${day}日 (${weekDay})`
  }
  
  const getSelectedTimeSlotDisplay = () => {
    const selectedSlot = allTimeSlots.value.find(slot => slot.id === selectedTimeSlot.value)
    return selectedSlot ? selectedSlot.time : ''
  }
  
  return {
    date: formatBookingDate(selectedDate.value),
    timeSlot: getSelectedTimeSlotDisplay(),
    visitorInfo: `${selectedPersonalInfo.value.name} · ${selectedPersonalInfo.value.gender} · ${selectedPersonalInfo.value.age}岁`,
    phone: selectedPersonalInfo.value.phone
  }
})

// 获取星期几
const getWeekDay = (dateString) => {
  const date = new Date(dateString)
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return weekdays[date.getDay()]
}

// 确认预约 - 显示确认弹窗
const confirmBooking = () => {
  if (!canSubmit.value) {
    ElMessage.error('请完善预约信息')
    return
  }

  if (!selectedPersonalInfo.value || !selectedPersonalInfo.value.phone) {
    ElMessage.error('请填写完整的个人信息，包括手机号')
    return
  }

  confirmBookingVisible.value = true
}

// 提交预约 - 真正的预约逻辑
const submitBooking = async () => {
  confirmBookingVisible.value = false
  
  try {
    showLoading('预约提交中', '正在为您处理预约信息，请稍候...')
    
    // 查找选中的时间段
    const selectedSlot = allTimeSlots.value.find(slot => slot.id === selectedTimeSlot.value)
    
    if (!selectedSlot) {
      hideLoading()
      ElMessage.error('请选择有效的时间段')
      return
    }
    
    // 准备预约数据
    const bookingData = {
      timeSlotId: selectedTimeSlot.value,
      userToken: userToken.value,
      contactName: selectedPersonalInfo.value.name,
      contactPhone: selectedPersonalInfo.value.phone,
      notes: `性别：${selectedPersonalInfo.value.gender || ''}，年龄：${selectedPersonalInfo.value.age || ''}，学历：${selectedPersonalInfo.value.education || ''}`,
      specialRequirements: selectedPersonalInfo.value.occupation ? `职业：${selectedPersonalInfo.value.occupation}` : ''
    }
    
    console.log('提交预约数据:', bookingData)
    
    // 调用预约接口
    const response = await bookTimeSlot(bookingData)
    
    hideLoading()
    
    if (response.code === 200) {
      const bookingNumber = response.data
      
      // 准备预约详情数据
      const bookingDetailsData = {
        bookingInfo: {
          date: bookingSummary.value.date,
          timeSlot: selectedSlot.time,
          visitorCount: 1,
          bookingNumber: bookingNumber
        },
        visitorInfo: {
          name: selectedPersonalInfo.value.name,
          gender: selectedPersonalInfo.value.gender || '未填写',
          age: selectedPersonalInfo.value.age || '未填写',
          education: selectedPersonalInfo.value.education || '未填写',
          occupation: selectedPersonalInfo.value.occupation || '',
          phone: selectedPersonalInfo.value.phone
        }
      }
      
      ElMessage.success(`预约成功！预约编号：${bookingNumber}`)
      
      // 重新加载时间段数据以更新显示
      await loadTimeSlots(selectedDate.value)
      
      // 延迟跳转到预约详情页面
      setTimeout(() => {
        emit('showBookingDetails', bookingDetailsData)
      }, 1000)
      
    } else {
      ElMessage.error(response.message || '预约失败，请稍后重试！')
    }
    
  } catch (error) {
    hideLoading()
    console.error('预约失败:', error)
    ElMessage.error(error.response?.data?.message || error.message || '预约失败，请稍后重试')
  }
}

// 返回上一页
const goBack = () => {
  emit('switchTab', 'gallery')
}

// 初始化时加载数据
onMounted(async () => {
  // 生成或获取用户标识
  userToken.value = getUserToken()
  console.log('用户设备标识:', userToken.value)
  
  // 主动加载用户的个人信息
  await loadUserPersonalInfo()
  
  // 找到第一个可预约的日期
  const currentDate = getCurrentDate()
  const startDate = new Date(2025, 5, 25) // 2025年6月25日
  
  let initialDate
  if (currentDate >= startDate) {
    initialDate = formatDate(currentDate)
  } else {
    initialDate = formatDate(startDate)
  }
  
  // 确保选择的日期是可预约的
  if (isDateBookable(initialDate)) {
    selectedDate.value = initialDate
    loadTimeSlots(initialDate)
  } else {
    // 寻找下一个可预约日期
    const searchDate = new Date(startDate)
    const endDate = new Date(2025, 6, 23)
    
    while (searchDate <= endDate) {
      const dateStr = formatDate(searchDate)
      if (isDateBookable(dateStr)) {
        selectedDate.value = dateStr
        loadTimeSlots(dateStr)
        break
      }
      searchDate.setDate(searchDate.getDate() + 1)
    }
  }
})
</script>

<style scoped>
@import '../assets/css/booking/ticket.css';
</style> 